/*
 * @Author: wangrui 1249693143@qq.com
 * @Date: 2025-08-11 09:55:42
 * @LastEditors: wangrui 1249693143@qq.com
 * @LastEditTime: 2025-08-11 16:19:10
 * @FilePath: \draggable-chart-demo\src\util\index.js
 * @Description: 
 * 
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved. 
 */
// 获取节点连接点的坐标
export const getConnectionPoint = function (node, point) {

    const { x, y, style } = node
    const { width, height } = style
    switch (point) {
        case 'top':
            return { x: x + width / 2, y }
        case 'right':
            return { x: x + width, y: y + height / 2 }
        case 'bottom':
            return { x: x + width / 2, y: y + height }
        case 'left':
            return { x, y: y + height / 2 }
        default:
            return { x: x + width / 2, y: y + height / 2 }
    }
}

// 计算两个点之间的距离
export const distance = function (p1, p2) {
    const dx = p1.x - p2.x
    const dy = p1.y - p2.y
    return Math.sqrt(dx * dx + dy * dy)
}
// 计算两个节点之间最近的连接点
export const getClosestConnectionPoint = function (sourceNode, targetNode) {
    const sourcePoints = ['top', 'right', 'bottom', 'left']
    const targetPoints = ['top', 'right', 'bottom', 'left']
    let minDistance = Infinity
    let closestPoint = null
    for (const sourcePoint of sourcePoints) {
        const sourcePointCoords = getConnectionPoint(sourceNode, sourcePoint)
        for (const targetPoint of targetPoints) {
            const targetPointCoords = getConnectionPoint(targetNode, targetPoint)
            const dist = distance(sourcePointCoords, targetPointCoords)
            if (dist < minDistance) {
                minDistance = dist
                closestPoint = {
                    source: sourcePointCoords,
                    target: targetPointCoords,
                    sourcePoint,
                    targetPoint,
                    dist
                }
            }
        }
    }
    return closestPoint
}


//判断当前坐标是否在节点内部
export const isPointInNode = function (node, point) {
    const { x, y, style } = node
    const { width, height } = style
    const { x: pointX, y: pointY } = point
    return pointX >= x && pointX <= x + width && pointY >= y && pointY <= y + height
}

//判断当前坐标是否在连接点附近
export const isPointNearConnectionPoint = function (targetXY, targetPointXYList) {
    for (const targetPointXY of targetPointXYList) {
        if (distance(targetXY, targetPointXY.trget) < 50) {
            return {
                targetPoint: targetPointXY,
                isPointNearConnectionPoint: true
            }
        }
    }
    return false
}

